import os
import shutil
from myfun import read_pic,save_pic,show_pic,check_dir
import cv2
import numpy as np
import matplotlib.pyplot as plt
import copy

#首先读取一下图片 显示出来先
src=r'C:\Users\Administrator\Desktop\高品'
des=src+r"结果"
check_dir(des)

# i=0
h=256
# i_lst=[]#用list来计数
for file in os.listdir(src):
    # if i==0:
    print(file,'\t',type(file))
    #试一下用cv读取并显示图片
    pic_read=read_pic(src,file)#读取一下图片
    print(type(pic_read))
    bder = cv2.copyMakeBorder(pic_read, 256, 256, 256, 256, borderType=cv2.BORDER_CONSTANT, value=[255, 255, 255])
    #显示图片
    #show_pic(pic_read,file)
    fig, ax = plt.subplots()
    ax.imshow(cv2.cvtColor(pic_read, cv2.COLOR_BGR2RGB))
    j=[]
    def button_press(event):
        if event.button == 1:  # 点击了鼠标左键
            j.append(0)
            print("点击了鼠标左键")
            ax.cla()
            #ax = event.inaxes
            x, y = int(event.xdata), int(event.ydata)
            print("点击之后的x和y分别是:", x, '\t', y)
            x1, y1 = int(x - h / 2), int(y - h / 2)
            x2, y2 = int(x + h / 2), int(y + h / 2)

            cv2.rectangle(pic_read, (x1, y1), (x2, y2), (0, 0, 0), 5)

            x1, x2, y1, y2 = x1 + 256, x2 + 256, y1 + 256, y2 + 256
            #imgCopy = read_pic(src,file)
            #在复制的图上去画框，下面显示的时候 也是显示复制的图片 从原图上去保存图片


            #在原图上去切片吧
            # xmax, ymax = imgCopy.shape[1], imgCopy.shape[0]
            # x1 = x1 if x1 >= 0 else 0
            # y1 = y1 if y1 >= 0 else 0
            # x2 = x2 if x2 <= xmax else xmax
            # y2 = y2 if y2 <= ymax else ymax

            ball = bder[y1:y2, x1:x2]
            save_pic(ball,des,file.replace('.','_'+str(len(j))+'.'))
            ax.imshow(cv2.cvtColor(pic_read, cv2.COLOR_BGR2RGB))
            plt.title(file)
            fig.canvas.draw_idle()

    fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)  # 取消默认快捷键的注册
    fig.canvas.mpl_connect('button_press_event', button_press)  # 鼠标点击
    plt.title(file)
    plt.show()

#是可以正常的读取并且显示图片的，下一步就是用鼠标事件了

